/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package shellCommands;
import Sessions.EcomAdminRemote;
import Sessions.EcomCustomersRemote;
import entityBeans.Products;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.rmi.RemoteException;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author SOGOBA
 */
public class CartCommand implements InterShell{
    private ContextCommande cxtCmd;
   

       
    public CartCommand(ContextCommande ContextCommand){
          cxtCmd =  ContextCommand;
    }

    @Override
    public Commands getName() {
        return Commands.cart;
    }

    @Override
    public String getShortDescription() {
     String description = "Manage a cart \n";
        description += "\t  : without argument...................................list product of your cart \n";
        description += "\t  : -add [Id product] .................................add product in the cart \n";
        description += "\t  : -buy [Nummero IBAN] ...................................... buy the cart\n";
        description += "\t  : -clear ............................................. clear your cart\n";

        return description;
    }

    @Override
 public void execute(String cmd,EcomAdminRemote ecomAdmin,EcomCustomersRemote ecomCust) throws RemoteException {
            StringTokenizer st = new StringTokenizer(cmd, " ");
            // Ignore la commande
            st.nextToken();
            // sans argument, on liste les produits du caddie en cours
            if (st.countTokens() == 0) {
                //List<CartItem> cartItem = cartL.getItems(cartId);
                System.out.println("Vous avez " + ecomCust.getCart().size()+ " produit(s)  dans votre caddie. \n \n");
               if (cxtCmd.getVar("output")=="XML"){
                   System.out.println(getXML(ecomCust));
               }
                else{
                    System.out.println(getText(ecomCust));
                }                
            } else {
                String option = st.nextToken();
                // ajout d'un produit dans un caddie
                switch (option) {
                    case "-add":
                        if (st.countTokens() == 1) {
                                int idProd = Integer.valueOf(st.nextToken());
                                ecomCust.addCart(idProd);
                                System.out.println("Your product has been successfully added.");

                        } else {
                            System.out.println("Command is not avalaible");
                        }
                        break;
                    case "-remove":
                        if (st.countTokens() == 1) {
                          
                                int idProd = Integer.valueOf(st.nextToken());
                                ecomCust.removeCart(idProd);
                                System.out.println("Your product was successfully removed");

                        } else {
                            System.out.println("Command is not avalaible");
                        }
                        break;
                    case "-buy":
                        if (st.countTokens() == 1) {
                            String cmp=st.nextToken();
                            ecomCust.byuCart(cmp);
//                           System.out.println(ecomCust.getEtat());

                                //cartLocal.clear(cartId);
                         } else {
                            System.out.println("Command is not avalaible");
                        }
                        break;
                    case "-clear":
                        if (st.countTokens() == 0) {
                            try {
                                ecomCust.CartClear();
                                System.out.println("Your cart was cleared.");
                            } catch (Exception ex) {
                                System.out.println("Error with clearing your cart");
                            }
                        } else {
                            System.out.println("Command is not avalaible");
                        }
                        break;
                    default:
                        System.out.println("\t" + option + " is not known for Cart Management");
                        break;
                }
            }
      }

    @SuppressWarnings("CallToThreadDumpStack")
  public String getXML(EcomCustomersRemote ecomCustomerBean){
     String xmlString=""; 
        try {
            // Create Document factory
            DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();
            // Create document
            DocumentBuilder constructeur = fabrique.newDocumentBuilder();
            // Read a file XML with DOM
            File xml = new File("C:/Users/SOGOBA/Documents/NetBeansProjects/StoreEcom/StoreEcom-app-client/src/java/storeecom/XMLDocument.xml");
            Document document = constructeur.parse(xml);
            // Cr�ation de l'arborescence du DOM
            Element racine = document.getDocumentElement();
            racine.appendChild(document.createComment("My cart contains "));
            Element cart = document.createElement("Cart");
            racine.appendChild(cart);
            // Get all products contains in the cart
            for (Products prod : ecomCustomerBean.getCart()) {
                Element p = document.createElement("Product");
                cart.appendChild(p);
                Element storeId = document.createElement("productStoreId");
                storeId.setTextContent(prod.getIdProductsstoreFk().toString());
                p.appendChild(storeId);
                Element prodId = document.createElement("reference");
                prodId.setTextContent(prod.getReferenceProd().toString());
                p.appendChild(prodId);
                Element name = document.createElement("name");
                name.setTextContent(prod.getNameProd());
                p.appendChild(name);
                Element price = document.createElement("price");
                price.setAttribute("currency", cxtCmd.getVar("currency").toString());
                price.setTextContent(ecomCustomerBean.getConverToEuro(prod.getPriceProd(),cxtCmd.getVar("currency").toString()).toString());
                p.appendChild(price);
            }
                Element total=document.createElement("total");
                total.setAttribute("currency", cxtCmd.getVar("currency").toString());
                total.setTextContent(ecomCustomerBean.getConverToEuro(ecomCustomerBean.totalCart(),cxtCmd.getVar("currency").toString()).toString());
                DOMSource domSource = new DOMSource(document);
                StringWriter writer = new StringWriter();
                StreamResult result = new StreamResult(writer);
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer transformer = tf.newTransformer();
                transformer.transform(domSource, result);
                xmlString = writer.toString();
        }
        catch (IOException | ParserConfigurationException ex) {
            Logger.getLogger(CartCommand.class.getName()).log(Level.SEVERE, null, ex);
        }
    catch(Exception e){
            e.printStackTrace();
          }
    return xmlString;

}

public String getText (EcomCustomersRemote ecomCustomerBean){
        String textString="List of all cart's products \n";
    
    try {
            for (Products prod : ecomCustomerBean.getCart()){
               textString+="Store Id : "+ prod.getIdProductsstoreFk() +"Id product : "+ prod.getReferenceProd()+ "name : "+ prod.getNameProd()+ "Price currency: "+cxtCmd.getVar("currency")+ "Value : "+ ecomCustomerBean.getConverToEuro(prod.getPriceProd(),cxtCmd.getVar("currency").toString()).toString()+ "\n";
            }
            textString+="total : "+ecomCustomerBean.getConverToEuro(ecomCustomerBean.totalCart(),cxtCmd.getVar("currency").toString()).toString();
            return textString;
        } catch (RemoteException ex) {
            Logger.getLogger(CartCommand.class.getName()).log(Level.SEVERE, null, ex);
        }
    return textString;
}
 
}


